#include "fig_shakescreen.h"

#include "num/rand.h"

void	FIGShakeScreen::Tick(float dt)
{
	if(m_State == SHAKE_STATE_NONE)
		return;

	const float Target = m_Intensity * 0.005f;
	const float SHAKE_SPEED = 0.20f;

	if(m_State == SHAKE_STATE_BACKTONORMAL)
	{
		bool IsReachBack = false;
		if(m_CurrentShakeOffset.y >= 0)
		{
			m_CurrentShakeOffset.y -= dt;
			if(m_CurrentShakeOffset.y <=0)
			{
				IsReachBack = true;		
				m_CurrentShakeOffset.y = 0;
			}
		}

		if(m_CurrentShakeOffset.y <= 0)
		{
			m_CurrentShakeOffset.y += dt;
			if(m_CurrentShakeOffset.y >=0)
			{
				IsReachBack = true;
				m_CurrentShakeOffset.y = 0;
			}
		}

		if(IsReachBack || m_CurrentShakeOffset.y == 0)
		{
			m_CurrentShakeOffset.y = 0;
			m_TotalShakeCount--;			
			if(m_TotalShakeCount <= 0)
			{
				m_TotalShakeCount  = 0;
				m_State = SHAKE_STATE_NONE;
			}
			else
			{
				if( m_PreviousState == SHAKE_STATE_PLUS)
					m_State = SHAKE_STATE_MINUS;
				else if( m_PreviousState == SHAKE_STATE_MINUS)
					m_State = SHAKE_STATE_PLUS;
			}
		}		
	}

	else if( m_State == SHAKE_STATE_PLUS)
	{
		m_CurrentShakeOffset.y += (dt * SHAKE_SPEED);
		if(m_CurrentShakeOffset.y >= Target )
		{
			m_CurrentShakeOffset.y = Target; 
			m_PreviousState = m_State;
			m_State = SHAKE_STATE_BACKTONORMAL;
		}
	}

	else if( m_State == SHAKE_STATE_MINUS)
	{
		m_CurrentShakeOffset.y -= (dt * SHAKE_SPEED);		
		if(m_CurrentShakeOffset.y <= -Target )
		{
			m_CurrentShakeOffset.y = -Target; 
			m_PreviousState = m_State;
			m_State = SHAKE_STATE_BACKTONORMAL;
		}
	}
}

void	FIGShakeScreen::Shake(float Intensity)
{
	m_Intensity = Intensity;

	if( m_State == SHAKE_STATE_NONE)
	{
		if(num::RAND32::Instance().RandInt(0,1) == 0)
			m_State = SHAKE_STATE_PLUS;
		else
			m_State = SHAKE_STATE_MINUS;
	}

	m_TotalShakeCount = 4 + (int)Intensity;
}

FIGShakeScreen::FIGShakeScreen() : m_TotalShakeCount(0),
							 m_DelayNextShake(0),
							 m_Intensity(0),
							 m_State(SHAKE_STATE_NONE),
							 m_PreviousState(SHAKE_STATE_NONE)
{
	

}

